package com.yingpai.fitness.dvp_2_0.main.fragment.mine.shop;

import android.app.AlertDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.lzy.okgo.model.HttpParams;
import com.lzy.okgo.model.Response;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.yingpai.fitness.R;
import com.yingpai.fitness.base.BaseResponse;
import com.yingpai.fitness.dvp_2_0.common.adapter.BaseAdapterHelper;
import com.yingpai.fitness.dvp_2_0.common.adapter.QuickAdapter;
import com.yingpai.fitness.dvp_2_0.common.finalokgo.callback.Callback;
import com.yingpai.fitness.dvp_2_0.common.finalokgo.request.RequestType;
import com.yingpai.fitness.dvp_2_0.common.fragment.CommonFragment;
import com.yingpai.fitness.dvp_2_0.common.util.GsonUtil;
import com.yingpai.fitness.dvp_2_0.common.util.SharedPreferencesHelp;
import com.yingpai.fitness.dvp_2_0.common.util.constant.Contacts;
import com.yingpai.fitness.dvp_2_0.common.view.XListView;
import com.yingpai.fitness.dvp_2_0.main.activity.shop.ShopDetailActivity;
import com.yingpai.fitness.dvp_2_0.main.bean.Dvp_2_1_OrderListBean;
import com.yingpai.fitness.dvp_2_0.main.bean.pay.ChongZhiDingDanEntiy;
import com.yingpai.fitness.dvp_2_0.main.bean.pay.ZfbChongZhiEntity;
import com.yingpai.fitness.dvp_2_0.main.callback.WechatCallBack;
import com.yingpai.fitness.dvp_2_0.main.util.DialogUtil;
import com.yingpai.fitness.dvp_2_0.main.util.PayUtil;
import com.yingpai.fitness.dvp_2_0.main.util.WechatLoginUtil;
import com.yingpai.fitness.dvp_2_0.main.util.constant.Constant;
import com.yingpai.fitness.dvp_2_0.main.util.constant.Url;
import com.yingpai.fitness.dvp_2_0.main.widget.round.RCRelativeLayout;
import com.yingpai.fitness.entity.ShopDetailMcipChildBean;
import com.yingpai.fitness.entity.wx.TokenBean;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * Created by ASUS on 2018/11/23.
 */

public class WaitPayOrderListFragment extends CommonFragment implements OnRefreshLoadMoreListener, PayUtil.codeResultClickInterface, WechatCallBack {

    @BindView(R.id.listview)
    ListView listView;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.empty)
    LinearLayout empty;
    @BindView(R.id.title_bar)
    RelativeLayout title_bar;
    Unbinder unbinder;
    private String status;
    private QuickAdapter<Dvp_2_1_OrderListBean.DataBean.PageInfoBean.ListBeanX> quickAdapter;
    private TokenBean tokenBean;
    private int pageNum = 1;
    private int pageSize = 10;
    private String tag = "";
    private int orderId;
    private DecimalFormat df = new DecimalFormat("######.###");

    public static WaitPayOrderListFragment newInstance(String status) {
        WaitPayOrderListFragment orderListFragment = new WaitPayOrderListFragment();
        Bundle bundle = new Bundle();
        bundle.putString("status", status);
        orderListFragment.setArguments(bundle);
        return orderListFragment;
    }

    @Override
    protected View initView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.dvp_2_0_fragment_order_list, container, false);
        unbinder = ButterKnife.bind(this, view);
        title_bar.setVisibility(View.GONE);
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        refreshLayout.setOnRefreshLoadMoreListener(this);
        refreshLayout.setRefreshHeader(new MaterialHeader(context).setColorSchemeResources(R.color.common_color));
        tokenBean = (TokenBean) SharedPreferencesHelp.getBean(Constant.TOKENBEAN);
        status = getArguments().getString("status");

        quickAdapter = new QuickAdapter<Dvp_2_1_OrderListBean.DataBean.PageInfoBean.ListBeanX>(context, R.layout.dvp_2_1_item_order_list) {
            @Override
            protected void convert(final BaseAdapterHelper helper, final Dvp_2_1_OrderListBean.DataBean.PageInfoBean.ListBeanX pItem) {
                helper.setText(R.id.title, "订单号：" + pItem.getOrderCode());
                helper.setText(R.id.shop_count, "共" + pItem.getQuantity() + "件商品");
                helper.setText(R.id.money, "￥" + df.format(pItem.getTotalPrice() / 100));

                TextView right_tv = helper.getView(R.id.right_tv);
                TextView left_tv = helper.getView(R.id.left_tv);
                right_tv.setText("立即付款");
                left_tv.setText("取消订单");
                right_tv.setVisibility(View.VISIBLE);
                left_tv.setVisibility(View.VISIBLE);

                right_tv.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        DialogUtil.getInstance().showBottomDialog(WaitPayOrderListFragment.this.context, R.layout.bottom_pay_layout);
                        View dialog_layout = DialogUtil.getInstance().dialog_bottom_layout;
                        dialog_layout.findViewById(R.id.outImg).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                DialogUtil.getInstance().dialog_bottom.dismiss();
                            }
                        });

                        TextView payPriceTv = dialog_layout.findViewById(R.id.payPriceTv);
                        payPriceTv.setText("支付 ￥" + df.format((pItem.getTotalMerchandisePrice() + pItem.getTotalPostPrice()) / 100));

                        final CheckBox mWeChatPayCb = dialog_layout.findViewById(R.id.weChatPayCb);
                        final CheckBox mALiPayCb = dialog_layout.findViewById(R.id.aLiPayCb);

                        mWeChatPayCb.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                if (mWeChatPayCb.isChecked()) {
                                    tag = Constant.WECHAT;
                                    mALiPayCb.setChecked(false);
                                } else {
                                    tag = "";
                                }
                            }
                        });
                        mALiPayCb.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                if (mALiPayCb.isChecked()) {
                                    tag = Constant.ALIPAY;
                                    mWeChatPayCb.setChecked(false);
                                } else {
                                    tag = "";
                                }
                            }
                        });

                        Button goPayBtn = dialog_layout.findViewById(R.id.goPayBtn);

                        goPayBtn.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                if (tag.equals(Constant.ALIPAY)) {
                                    orderId = pItem.getOrderId();
                                    showDialog(WaitPayOrderListFragment.this.context, "支付中...");
                                    HttpParams httpParams = new HttpParams();
                                    httpParams.put("id", pItem.getOrderId());
                                    httpParams.put("customerId", tokenBean.getId());
                                    finalOkGo.request(RequestType.POST, Contacts.HOST_SERVER + Url.SHOP_ALI_PAY, httpParams, Url.SHOP_ALI_PAY, new Callback<ZfbChongZhiEntity>() {
                                        @Override
                                        public void onSuccess(ZfbChongZhiEntity zfbChongZhiEntity) {
                                            if (zfbChongZhiEntity.getResult().equals(Constant.REQUEST_SUCCESS)) {
                                                PayUtil.zfbpay(WaitPayOrderListFragment.this, WaitPayOrderListFragment.this.context, zfbChongZhiEntity.getMap().getResponse());
                                            } else {
                                                showToast(zfbChongZhiEntity.getMsg() + "");
                                            }
                                            DialogUtil.getInstance().dialog_bottom.dismiss();
                                        }
                                    });
                                } else if (tag.equals(Constant.WECHAT)) {
                                    orderId = pItem.getOrderId();
                                    showDialog(WaitPayOrderListFragment.this.context, "支付中...");
                                    HttpParams httpParams = new HttpParams();
                                    httpParams.put("id", pItem.getOrderId());
                                    httpParams.put("customerId", tokenBean.getId());
                                    finalOkGo.request(RequestType.POST, Contacts.HOST_SERVER + Url.SHOP_WECHAT_PAY, httpParams, Url.SHOP_WECHAT_PAY, new Callback<ChongZhiDingDanEntiy>() {
                                        @Override
                                        public void onSuccess(ChongZhiDingDanEntiy chongZhiDingDanEntiy) {
                                            if (chongZhiDingDanEntiy.getResult().equals(Constant.REQUEST_SUCCESS)) {
                                                WechatLoginUtil.getInstance().setWechatCallBack(WaitPayOrderListFragment.this);
                                                PayUtil.wxpay(WaitPayOrderListFragment.this.context, chongZhiDingDanEntiy.getMap().getResponse().getAppid(),
                                                        chongZhiDingDanEntiy.getMap().getResponse().getPartnerid(),
                                                        chongZhiDingDanEntiy.getMap().getResponse().getPrepayid(),
                                                        chongZhiDingDanEntiy.getMap().getResponse().getNoncestr(),
                                                        chongZhiDingDanEntiy.getMap().getResponse().getTimestamp() + "",
                                                        chongZhiDingDanEntiy.getMap().getResponse().getSign());
                                            } else {
                                                showToast(chongZhiDingDanEntiy.getMsg() + "");
                                            }
                                            DialogUtil.getInstance().dialog_bottom.dismiss();
                                        }
                                    });
                                } else {
                                    showToast("请选择支付方式");
                                }

                            }
                        });

                    }
                });

                left_tv.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        DialogUtil.getInstance().showCenterDialog(WaitPayOrderListFragment.this.context, R.layout.dialog_shop_pay_success);
                        View dialog_layout = DialogUtil.getInstance().dialog_center_layout;

                        TextView title = dialog_layout.findViewById(R.id.title);
                        title.setText("确定取消订单？");
                        TextView message = dialog_layout.findViewById(R.id.message);
                        message.setVisibility(View.GONE);
                        dialog_layout.findViewById(R.id.sure_cancel).setVisibility(View.VISIBLE);

                        dialog_layout.findViewById(R.id.close).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                DialogUtil.getInstance().dialog_center.dismiss();
                            }
                        });

                        dialog_layout.findViewById(R.id.sure).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                DialogUtil.getInstance().dialog_center.dismiss();
                                showDialog(WaitPayOrderListFragment.this.context, null);
                                HttpParams httpParams = new HttpParams();
                                httpParams.put("id", pItem.getOrderId());
                                finalOkGo.request(RequestType.POST, Contacts.HOST_SERVER + Url.CANCEL_ORDER, httpParams, Url.CANCEL_ORDER, new Callback<BaseResponse>() {
                                    @Override
                                    public void onSuccess(BaseResponse baseResponse) {
                                        dismissDialog();
                                        if (baseResponse.getResult().equals(Constant.REQUEST_SUCCESS)) {
                                            onRefresh(refreshLayout);
                                        } else {
                                            showToast(baseResponse.getMsg());
                                        }
                                    }
                                });
                            }
                        });
                        dialog_layout.findViewById(R.id.cancel).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                DialogUtil.getInstance().dialog_center.dismiss();
                            }
                        });
                    }
                });

                XListView child_listview = helper.getView(R.id.child_listview);
                QuickAdapter<Dvp_2_1_OrderListBean.DataBean.PageInfoBean.ListBeanX.DetailListBean> child_adapter =
                        new QuickAdapter<Dvp_2_1_OrderListBean.DataBean.PageInfoBean.ListBeanX.DetailListBean>(context, R.layout.dvp_2_1_item_child_order_list) {
                            @Override
                            protected void convert(BaseAdapterHelper helper, Dvp_2_1_OrderListBean.DataBean.PageInfoBean.ListBeanX.DetailListBean cItem) {
                                helper.setText(R.id.title, cItem.getBrandName());

                                XListView child_listview_1 = helper.getView(R.id.child_listview_1);

                                QuickAdapter<Dvp_2_1_OrderListBean.DataBean.PageInfoBean.ListBeanX.DetailListBean.ListBean> child_adapter_1 =
                                        new QuickAdapter<Dvp_2_1_OrderListBean.DataBean.PageInfoBean.ListBeanX.DetailListBean.ListBean>(context, R.layout.item_child_order_list, cItem.getList()) {
                                            @Override
                                            protected void convert(BaseAdapterHelper helper, final Dvp_2_1_OrderListBean.DataBean.PageInfoBean.ListBeanX.DetailListBean.ListBean cItem1) {
                                                helper.getView(R.id.item_rl).setOnClickListener(new View.OnClickListener() {
                                                    @Override
                                                    public void onClick(View v) {
                                                        Bundle bundle = new Bundle();
                                                        bundle.putInt("id", cItem1.getMerchandiseId());
                                                        startActivity(ShopDetailActivity.class, bundle);
                                                    }
                                                });
                                                helper.setText(R.id.title, cItem1.getMerchandiseName());
                                                helper.setText(R.id.money, "￥" + df.format(cItem1.getSinglePrice() / 100));
                                                List<ShopDetailMcipChildBean> mcipList = GsonUtil.jsonToList(cItem1.getMcipValue(), ShopDetailMcipChildBean.class);
                                                StringBuilder stringBuilder = new StringBuilder();
                                                for (int i = 0; i < mcipList.size(); i++) {
                                                    if (i == mcipList.size() - 1) {
                                                        stringBuilder.append(mcipList.get(i).getPropertyValue());
                                                    } else {
                                                        stringBuilder.append(mcipList.get(i).getPropertyValue() + ";");
                                                    }
                                                }
                                                helper.setText(R.id.num_spec, "数量：x" + cItem1.getPurchaseAmount() + ";" + stringBuilder.toString());
                                                RCRelativeLayout rc_layout = helper.getView(R.id.rc_layout);
                                                ImageView photo = helper.getView(R.id.photo);
                                                Glide.with(WaitPayOrderListFragment.this.context)
                                                        .load(cItem1.getPhotoUrl())
                                                        .error(R.mipmap.default_small_bg)
                                                        .into(photo);
                                                rc_layout.setTopLeftRadius(6);
                                                rc_layout.setTopRightRadius(6);
                                                rc_layout.setBottomLeftRadius(6);
                                                rc_layout.setBottomRightRadius(6);
                                                TextView return_money_goods = helper.getView(R.id.return_money_goods);
                                                return_money_goods.setVisibility(View.GONE);
                                            }
                                        };

                                child_listview_1.setAdapter(child_adapter_1);
                            }
                        };
                child_listview.setAdapter(child_adapter);
                if (pItem.getDetailList() != null) {
                    child_adapter.clear();
                    child_adapter.addAll(pItem.getDetailList());
                    child_adapter.notifyDataSetChanged();
                }
            }
        };

        listView.setAdapter(quickAdapter);

        return view;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

    @Subscribe(threadMode = ThreadMode.POSTING)
    public void OnMessageEvent(String s) {
        if (s.equals("updateOrderList")) {
            pageNum = 1;
            initData();
        }else if(s.equals("0")){
            pageNum = 1;
            initData();
        }
    }

    @Override
    protected void initData() {
//        showDialog(context, null);
        HashMap<String, Object> httpParams = new HashMap();
        httpParams.put("status", status);
        httpParams.put("pageNum", pageNum++);
        httpParams.put("pageSize", pageSize);
        finalOkGo.requestEncrypt(RequestType.POSTENCRYPT, Contacts.HOST_SERVER + Url.ORDER_LIST, httpParams, Url.ORDER_LIST, new Callback<Dvp_2_1_OrderListBean>() {
            @Override
            public void onSuccess(Dvp_2_1_OrderListBean orderListBean) {
                if (orderListBean.getCode().equals(Constant.REQUEST_SUCCESS_0) && orderListBean.getData() != null && orderListBean.getData().getPageInfo().getList() != null && orderListBean.getData().getPageInfo().getList().size() != 0) {
                    refreshLayout.setNoMoreData(false);
                    if (pageNum - 1 == 1) {
                        quickAdapter.clear();
                        for (int i = 0; i < orderListBean.getData().getPageInfo().getList().size(); i++) {
                            if (orderListBean.getData().getPageInfo().getList().get(i).getStatus() == 0) {
                                quickAdapter.add(orderListBean.getData().getPageInfo().getList().get(i));
                            }
                        }
                    } else {
                        for (int i = 0; i < orderListBean.getData().getPageInfo().getList().size(); i++) {
                            if (orderListBean.getData().getPageInfo().getList().get(i).getStatus() == 0) {
                                quickAdapter.add(orderListBean.getData().getPageInfo().getList().get(i));
                            }
                        }
                    }
                    if (quickAdapter.getCount() > 0) {
                        empty.setVisibility(View.GONE);
                    } else {
                        empty.setVisibility(View.VISIBLE);
                    }
                } else {
                    if (pageNum - 1 == 1) {
                        quickAdapter.clear();
                        empty.setVisibility(View.VISIBLE);
                    } else {
                        if (quickAdapter.getCount() > 0) {
                            empty.setVisibility(View.GONE);
                        } else {
                            empty.setVisibility(View.VISIBLE);
                        }
                    }
                    refreshLayout.finishLoadMoreWithNoMoreData();
                }

                refreshLayout.finishRefresh();
                refreshLayout.finishLoadMore();
                quickAdapter.notifyDataSetChanged();
//                dismissDialog();
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
//                dismissDialog();
                if (pageNum - 1 == 1) {
                    empty.setVisibility(View.VISIBLE);
                } else {
                    empty.setVisibility(View.GONE);
                }
            }
        });
    }

    @Override
    @OnClick({R.id.empty})
    public void onViewClicked(View view) {
        super.onViewClicked(view);
        switch (view.getId()) {
            case R.id.empty:
                onRefresh(refreshLayout);
                break;
        }
    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        initData();
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        pageNum = 1;
        initData();
    }

    @Override
    public void ZFBSuccess(String code) {
        dismissDialog();
        HttpParams httpParams = new HttpParams();
        httpParams.put("customerId", tokenBean.getId());
        httpParams.put("orderId", orderId);
        httpParams.put("payMode", Constant.NUM_1 + "");
        finalOkGo.request(RequestType.POST, Contacts.HOST_SERVER + Url.SHOP_NOTIFY_PAY, httpParams, Url.SHOP_NOTIFY_PAY, new Callback<BaseResponse>() {
            @Override
            public void onSuccess(BaseResponse baseResponse) {
                if (baseResponse.getResult().equals(Constant.REQUEST_SUCCESS)) {
                    onRefresh(refreshLayout);
                    showPaySuccess();
                } else {
                    showFaileDialog();
                }
            }

            @Override
            public void onError(Response response) {
                super.onError(response);
                showFaileDialog();
            }
        });
    }

    @Override
    public void ZFBFail(String code) {
        dismissDialog();
    }

    @Override
    public void ZFBResultQueRen(String code) {

    }

    @Override
    public void callBack(BaseResp baseResp) {
        dismissDialog();
        if(baseResp.errCode != BaseResp.ErrCode.ERR_OK){
            return;
        }
        HttpParams httpParams = new HttpParams();
        httpParams.put("customerId", tokenBean.getId());
        httpParams.put("orderId", orderId);
        httpParams.put("payMode", Constant.NUM_2 + "");
        finalOkGo.request(RequestType.POST, Contacts.HOST_SERVER + Url.SHOP_NOTIFY_PAY, httpParams, Url.SHOP_NOTIFY_PAY, new Callback<BaseResponse>() {
            @Override
            public void onSuccess(BaseResponse baseResponse) {
                if (baseResponse.getResult().equals(Constant.REQUEST_SUCCESS)) {
                    onRefresh(refreshLayout);
                    showPaySuccess();
                } else {
                    showFaileDialog();
                }
            }

            @Override
            public void onError(Response response) {
                super.onError(response);
                showFaileDialog();
            }
        });
    }

    private void showPaySuccess() {
        DialogUtil.getInstance().showCenterDialog(context, R.layout.dialog_shop_pay_success);
        TextView message = DialogUtil.getInstance().dialog_center_layout.findViewById(R.id.message);
        message.setText("");
        message.setVisibility(View.INVISIBLE);
        DialogUtil.getInstance().dialog_center_layout.findViewById(R.id.close).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DialogUtil.getInstance().dialog_center.dismiss();
            }
        });
    }

    private void showFaileDialog() {
        LayoutInflater mInflater = LayoutInflater.from(context);
        LinearLayout dialog_pay_faile = (LinearLayout) mInflater.inflate(R.layout.dialog_pay_faile, null);
        Dialog dialog = new AlertDialog.Builder(context, R.style.NoBackGroundDialog).create();
        dialog.show();
        dialog.setContentView(dialog_pay_faile);
    }
}
